<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2020/9/8
 * Time: 10:11
 */

namespace app\common\controller;

use app\common\model\ShortMsg;
use think\Controller;
use think\Exception;

class AliSms extends Controller
{
    private $code = 'SMS_201652121';
    private $appid = 'LTAI4GCueNpwucf4tzGqUxwf';
    private $appsecret = 'Ni9dbjCYC2gukg5D8E433yzCJPfBeA';

    public function __construct() {
        header("Access-Control-Allow-Origin:*");
        header("Access-Control-Allow-Method:POST,GET");
    }

    public function sendSms($mobile,$name){
        vendor('aliyunsms.SignatureHelper','.php');
        $appid = $this->appid;
        $appsecret = $this->appsecret;
        $code = $this->code;
        $params = [
            'PhoneNumbers' => $mobile,//手机号
            'TemplateCode' => $code, //模板id
            'SignName' => 'UET石油',
            'TemplateParam' => [ //短信模板需要的 变量内容
                'name' => $name,
                'content'=>'UET66888'
            ]
        ];
        if(!empty($params["TemplateParam"]) && is_array($params["TemplateParam"])) {
            $params["TemplateParam"] = json_encode($params['TemplateParam'], JSON_UNESCAPED_UNICODE);
        }
        $data = [
            'msg'=> $params['TemplateParam'],
            'tel'=> $mobile,
            'create_datetime' => date('Y-m-d H:i:s')
        ];
        $helper = new \SignatureHelper();
        try{
            $content = $helper->request(
                      $appid,
                      $appsecret,
                      'dysmsapi.aliyuncs.com',
                      array_merge($params,[
                          "RegionId" => "cn-hangzhou",
                          "Action" => "SendSms",
                          "Version" => '2017-05-25'
                      ])
                  );
            $content = (array)$content; //将对象转为数组 返回
            if(!empty($content) && isset($content['Code']) && $content['Code'] == 'OK'){
                $data['type'] = 0;
            }else{
                $data['type'] = 1;
                $data['error_msg'] = json_encode($content, JSON_UNESCAPED_UNICODE);
            }
            ShortMsg::create($data);
            if($data['type'] == 1){
                return false;
            }
            return true;
        }catch (Exception $e){
            $data['error_msg'] = '短信发送失败，'.$e->getMessage();
            $data['type'] = 1;
            ShortMsg::create($data);
            return false;
        }
    }
}